import axios from 'axios'
import router from '../router'
import {Notification} from 'element-ui'
import store from '../store'
//import {edit_url} from '@/utils/url'
//console.log(edit_url)
//import auth from '@/utils/auth'
// "http://192.168.0.147:8080/web/"
// process.env.API_URL

var instance = axios.create({
  baseURL: process.env.API_URL ,
  headers: {
//  "Authorization": auth.getLocalStorage('CMS-TOKEN'),
    "Accept": "application/json"
  },
  timeout: 5000,
  transformResponse: [data => {
      return data
    }
  ]
})

instance.interceptors.request.use(config => {
    const splitKeyword = store.getters.type ? 'admin' : 'web'

    if (!store.getters.type && config.baseURL !== store.getters.apiAddress) {
      const url = config.url.split(splitKeyword)[1]
      config.baseURL = store.getters.apiAddress
      config.url = store.getters.apiAddress + url
    }

    if (store.getters.token) {
      config.headers.Authorization = `${store.getters.token}`
    }

    return config
}, err => {
  return Promise.reject(err)
})

instance.interceptors.response.use(res => {
  if (!res) {
    Notification({title: "请求失败", message: "请求失败,或者网络连接断开, 请稍后再试", type: "error"})
    return null
  }
  let data = JSON.parse(res.data)
  if (data.code && data.code == 419) {
    router.replace("/login")
  } else if (data.code && data.code > 200) {
    Notification({title: "数据请求错误", message: data.msg, type: "warning"})
    return null
  } else if (data.code && data.code == 200) {
    return data
  }
  return data
}, err => {
  Notification({title: "连接失败", message: "连接失败请稍后再试", type: "error"})
  return Promise.reject(err)
})

export const Fetch = instance
